package com.leyou.user.service.impl;

import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.user.config.PasswordConfig;
import com.leyou.user.dto.UserDTO;
import com.leyou.user.entity.User;
import com.leyou.user.mapper.UserMapper;
import com.leyou.user.service.UserService;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.leyou.common.constants.MQConstants.Exchange.SMS_EXCHANGE_NAME;
import static com.leyou.common.constants.MQConstants.RoutingKey.VERIFY_CODE_KEY;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    private String KEY_PREFIX = "user:code:phone:";
//     根据用户名或手机号来查询
//     * 查到false
//     * 没查到true
    @Override
    public Boolean check(String data, Integer type) {
        User record = new User();

        switch (type) {
            case 1:
                record.setUsername(data);
                break;
            case 2:
                record.setPhone(data);
                break;
            default:
                throw new LyException(ExceptionEnum.INVALID_PARAM_ERROR);
        }

        try {
            return this.userMapper.selectCount(record)!=1;
        } catch (Exception e) {
            throw new LyException(ExceptionEnum.INTERNAL_SERVER_ERROR);
        }
    }


//    发送短信验证码到mp
    @Override
    public void sendVerifyCode(String phone) {
        /*
        - 1）我们接收页面发送来的手机号码
        - 2）生成一个随机验证码
        - 3）将验证码保存在服务端
        - 4）发送短信，将验证码发送到用户手机

         */
        Map<Object, Object> msg = new HashMap<>();
        msg.put("phone",phone);

        // 生成验证码
        String code = RandomStringUtils.randomNumeric(6);
        msg.put("code",code);

//        reds中存了五分钟
        this.redisTemplate.opsForValue().set(KEY_PREFIX + phone,code,50, TimeUnit.HOURS);

        try {
//            this.amqpTemplate.convertAndSend(SMS_EXCHANGE_NAME,VERIFY_CODE_KEY,msg);
        } catch (AmqpException e) {
            e.printStackTrace();
        }


    }

//    验证码的比较
    @Override
    public void register(User user, String code) {
        // 1 校验验证码
        // 1.1 取出redis中的验证码
        String cacheCode = redisTemplate.opsForValue().get(KEY_PREFIX + user.getPhone());
        // 1.2 比较验证码
        if (!StringUtils.equals(code, cacheCode)) {
            throw new LyException(ExceptionEnum.INVALID_VERIFY_CODE);
        }

        // 2 对密码加密
        user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));

        // 3 写入数据库
        int count = userMapper.insertSelective(user);
        if (count != 1) {
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }

//        手动删除redis中缓存的验证码
        this.redisTemplate.delete(KEY_PREFIX + user.getPhone());
    }

//    根据用户名和密码查询用户
    @Override
    public UserDTO login(String username, String password) {
        // 1根据用户名查询
        User u = new User();
        u.setUsername(username);
        User user = userMapper.selectOne(u);
        // 2判断是否存在
        if (user == null) {
            // 用户名错误
            throw new LyException(ExceptionEnum.INVALID_USERNAME_PASSWORD);
        }

        // 3校验密码
        if(!bCryptPasswordEncoder.matches(password, user.getPassword())){
            // 密码错误
            throw new LyException(ExceptionEnum.INVALID_USERNAME_PASSWORD);
        }
        return BeanHelper.copyProperties(user, UserDTO.class);
    }
}
